<template>
  <view class="x-tree_hightlight-name">
    {{ left }}
    <text class="x-tree_hightlight-on">{{ middle }}</text>
    {{ right }}
  </view>
</template>
<script lang="ts" setup>
  import { ref, watch } from "vue";
  const left = ref("");
  const middle = ref("");
  const right = ref("");

  const props = defineProps({
    name: {
      type: String,
      default: "",
    },
    search: {
      type: String,
      default: "",
    },
  });

  watch(
    () => props.search,
    (newVal) => {
      if (!newVal) {
        // 没有search，不需要高亮
        left.value = props.name;
        middle.value = "";
        right.value = "";
        return;
      }
      // 有search，需要判断高亮
      let index = props.name.indexOf(newVal);
      if (index === -1) {
        // 找不到，不需要高亮
        left.value = props.name;
        middle.value = "";
        right.value = "";
        return;
      }
      left.value = props.name.substring(0, index);
      middle.value = props.name.substring(index, index + newVal.length);
      right.value = props.name.substring(
        index + newVal.length,
        props.name.length
      );
    },
    {
      immediate: true,
    }
  );
</script>
<style lang="less">
.x-tree_highlight-on,
.x-tree_hightlight-name {
    
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

}

.x-tree_hightlight-on {
    margin-left: 2rpx;
    margin-right: 2rpx;
    color: white;
    background-color: #007aff;
    display: inline-block;
}

</style>
